package com.company.psm.controller;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.company.psm.entity.Category;
import com.company.psm.entity.Gradient;
import com.company.psm.entity.Medicine;
import com.company.psm.entity.User;
import com.company.psm.service.CategoryManagement;
import com.company.psm.service.GradientManagement;
import com.company.psm.service.MedicineManagement;
import com.company.psm.service.UserManagement;
import com.company.psm.util.Util;


@Controller
@RequestMapping("/medicine")
public class MedicineController {

	@Autowired
	private GradientManagement gradientManagement;
	
	@Autowired
	private MedicineManagement medicineManagement;
	
	@Autowired
	private UserManagement userManagement;
	
	@Autowired
	private CategoryManagement categoryManagement;
	
	@RequestMapping(method = RequestMethod.GET, value = "list")
	public ModelAndView getAllMedicine(@RequestParam(value="listAll", required=false) String listAll,
			@RequestParam(value="searchKey", required=false) String searchKey
			) {
		List<Medicine> medicines = new ArrayList<Medicine>();
		Long storeId = getCurrentUser().getStore().getId();
		ModelAndView model = getModelData();
		if (listAll!=null && listAll.equals("listAllData")){
			medicines = medicineManagement.getMedicineByStoreId(storeId);
		}else{
			if(searchKey!=null){
				medicines = medicineManagement.search(searchKey,storeId);
				model.addObject("searchKey",searchKey);
			}
		}
		model.setViewName("/medicine/list");
		model.addObject("medicines",medicines);
		return model;
	}
	@RequestMapping(method = RequestMethod.GET, value = "create")
	public ModelAndView createNewMedicine(
			@RequestParam(value = "medicineName", required = false) String medicineName,
			@RequestParam(value = "description", required = false) String description,
			@RequestParam(value = "price", required = false) String price,
			@RequestParam(value = "quantity", required = false) String quantity,
			@RequestParam(value = "specialize", required = false) String specialize,
			@RequestParam(value = "contraindicated", required = false) String contraindicated,
			@RequestParam(value = "categoryID", required = false) String categoryId,
			@RequestParam(value = "gradientList", required = false) String gradientsList) {
		ModelAndView model = getModelData();
		Long storeId = getCurrentUser().getStore().getId();
		if(medicineName ==null || medicineName.equalsIgnoreCase("")){
			List<Medicine> medicines = medicineManagement.getAllMedicines();
			model.setViewName("/medicine/create");
			model.addObject("medicines", medicines);
			return model;
		}
		else{
			List<Gradient> gradients = new ArrayList<Gradient>();
			List<String> listNameGradient = Util.toInGradientName(gradientsList);
			for (String gradientName : listNameGradient) {
				gradients.add(gradientManagement.getGradientWithNameAndStoreId(gradientName, storeId));
			}
			medicineManagement.createNewMedicine(medicineName, description, price, quantity, storeId,gradients,specialize,contraindicated,categoryManagement.getById(categoryId));
			model.setViewName("/medicine/list");
			model.addObject("medicines", medicineManagement.getMedicineByStoreId(storeId));
			return model;
		}
	}
	
	@RequestMapping(method = RequestMethod.GET, value = "update")
	public ModelAndView updateMedicine(
			@RequestParam(value = "id", required = false) String id,
			@RequestParam(value = "updateMedicineName", required = false) String medicineName,
			@RequestParam(value = "updateDescription", required = false) String description,
			@RequestParam(value = "updatePrice", required = false) String price,
			@RequestParam(value = "updateQuantity", required = false) String quantity,
			@RequestParam(value = "updateSpecialize", required = false) String specialize,
			@RequestParam(value = "updateContraindicated", required = false) String contraindicated,
			@RequestParam(value = "updateCategoryId", required = false) String categoryId,
			@RequestParam(value = "updateGradientList", required = false) String gradientsList) {
		ModelAndView model = getModelData();;
		Long storeId = getCurrentUser().getStore().getId();
		List<Gradient> gradients = new ArrayList<Gradient>();

		List<String> listNameGradient = Util.toInGradientName(gradientsList);
		for (String gradientName : listNameGradient) {
			gradients.add(gradientManagement.getGradientWithNameAndStoreId(gradientName, storeId));
		}
		medicineManagement.updateMedicine(id, medicineName, description, price, quantity, storeId, gradients, specialize, contraindicated,categoryManagement.getById(categoryId));
		model.setViewName("/medicine/list");
		model.addObject("medicines", medicineManagement.getMedicineByStoreId(storeId));
		return model;
	}
	
	@RequestMapping(method=RequestMethod.GET,value = "searchAjax")
	public @ResponseBody String searchAjaxMedicine(@RequestParam(value="searchKey", required=false) String searchKey){
		System.err.println("Search medicine = " + searchKey);
		Long storeId = getCurrentUser().getStore().getId();
		List<Medicine> medicines = medicineManagement.search(searchKey,storeId);
	    JSONObject responseDetailsJson = new JSONObject();
	    JSONArray jsonArray = new JSONArray();
	    JSONObject formDetailsJson = new JSONObject();
	    for (Medicine medicine : medicines) {
	        formDetailsJson = new JSONObject();
	        formDetailsJson.put("id", medicine.getId());
	        formDetailsJson.put("name", medicine.getName());
	        formDetailsJson.put("description", medicine.getDescription());
	        formDetailsJson.put("price", medicine.getPrice());
	        formDetailsJson.put("quantity", medicine.getQuantity());
	        jsonArray.put(formDetailsJson);
		}
	    responseDetailsJson.put("forms", jsonArray);
		return jsonArray.toString();
	}
	@RequestMapping(method=RequestMethod.GET,value = "search")
	public ModelAndView searchMedicine(@RequestParam(value="searchKey", required=false) String searchKey){
		ModelAndView model = getModelData();
		if(getCurrentUser().getRole().getCode().equals("ROLE_SALE_STAFF")){
			model.setViewName("/medicine/staffviewmedicine");
		}else{
			model.setViewName("/medicine/list");
		}
		Long storeId = getCurrentUser().getStore().getId();
		List<Medicine> medicines = medicineManagement.search(searchKey,storeId);
		model.addObject("searchKey",searchKey);
		model.addObject("medicines",medicines);
		return model;
	}
	
    public User getCurrentUser(){
    	Authentication authentication = SecurityContextHolder.getContext().
      		  getAuthentication();
      		  String name = authentication.getName();
      	return userManagement.getUserByAccount(name);
    }
    @RequestMapping(method=RequestMethod.GET,value = "gradientname")
    public @ResponseBody String getGradientName(String id){
		List<String> gradientNames = new ArrayList<String>();
		String gradientString = "";
		Medicine medicine = medicineManagement.getMedicineById(Long.parseLong(id));
		for (Gradient gradient : medicine.getGradients()) {
			gradientString += gradient.getName() + ",";
		}
		JSONObject responseDetailsJson = new JSONObject();
	    JSONArray jsonArray = new JSONArray();
	    JSONObject formDetailsJson = new JSONObject();
        formDetailsJson = new JSONObject();
        formDetailsJson.put("gradientString", gradientString);
        jsonArray.put(formDetailsJson);
	    responseDetailsJson.put("forms", jsonArray);
		return jsonArray.toString();
    }
	@RequestMapping(method=RequestMethod.GET,value = "role")
	public @ResponseBody String getRole(){
		String role = getCurrentUser().getRole().getCode();
	    JSONObject responseDetailsJson = new JSONObject();
	    JSONArray jsonArray = new JSONArray();
	    JSONObject formDetailsJson = new JSONObject();
        formDetailsJson = new JSONObject();
        formDetailsJson.put("role", role);
        jsonArray.put(formDetailsJson);
	    responseDetailsJson.put("forms", jsonArray);
		return jsonArray.toString();
	}
	
	@RequestMapping(method = RequestMethod.GET, value = "adminstore")
	public ModelAndView getAllAdminMedicine(@RequestParam(value="listAll", required=false) String listAll,
			@RequestParam(value="searchKey", required=false) String searchKey
			) {
		List<Medicine> medicines = new ArrayList<Medicine>();
		Long storeId = Util.ADMIN_STORE_ID;
		ModelAndView model = new ModelAndView();
		if (listAll!=null && listAll.equals("listAllData")){
			medicines = medicineManagement.getMedicineByStoreId(storeId);
		}else{
			if(searchKey!=null){
				medicines = medicineManagement.search(searchKey,storeId);
				model.addObject("searchKey",searchKey);
			}
		}
		model.setViewName("/medicine/adminstore");
		model.addObject("medicines",medicines);
		model.addObject("gradients",gradientManagement.getListOfGradientsByStoreId(storeId));
		return model;
	}
	
	@RequestMapping(method = RequestMethod.GET, value = "addToStore")
	public ModelAndView addMedicineToStore(
			@RequestParam(value = "listId", required = false) String listId) {
		ModelAndView model = new ModelAndView();
		Long storeId = getCurrentUser().getStore().getId();
		List<String> listMedicine = Util.toMedicineId(listId);
		for (String medicine : listMedicine) {
			medicineManagement.addMedicineToStore(medicine, storeId);
		}
		model.setViewName("/medicine/list");
		model.addObject("medicines", medicineManagement.getMedicineByStoreId(storeId));
		return model;
	}
	
	@RequestMapping(method=RequestMethod.GET, value = "delete")
	public ModelAndView delete(@RequestParam(value="id", required=false) String medicineId){
		try{
			medicineManagement.deleteMedicine(Long.parseLong(medicineId));
		}
		catch(Exception ex){
			ex.printStackTrace();
		}
		Long storeId = getCurrentUser().getStore().getId();
		List<Medicine> medicinesmedicines = medicineManagement.getMedicineByStoreId(storeId);
		return new ModelAndView("/medicine/list", "medicines",medicinesmedicines);
	}
	
	public ModelAndView getModelData(){
		ModelAndView model = new ModelAndView();
		Long storeId = getCurrentUser().getStore().getId();
		List<Category> categories = categoryManagement.getAllByStore(storeId);
		model.addObject("gradients",gradientManagement.getListOfGradientsByStoreId(storeId));
		model.addObject("categories",categories);
		return model;
	}
}
